using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using DICE_GS;

public enum MsgBoxCloseType
{
	Destroy,
	GotoLoginScene
}

public enum MapList
{
	none,
	tutorial,
	pvp1,
	pvp2,
	pvp3,
	pve1_1,
	pve1_2,
	pve1_3,
	pve1_4,
	pve1_5,
	pve1_6,
	pve1_7,
	pve2_1,
	pve2_2,
	pve2_3,
	pve2_4,
	pve2_5,
	pve2_6,
	pve2_7,
}

public enum SCENE
{
    LoadingScene = 0,
    CharacterSelectScene = 1,
    MainScene = 2,
    DeckEditScene = 6,
    UnitInvenScene = 7,
    UnitChangeConfirmScene = 8,
    SummonMenuScene = 9,
    SummonCommonScene = 10,
    SummonRareScene = 11,
    SummonResultScene = 12,
    UnitMenuScene = 13,
    UnitLevelupScene = 14,
    UnitEvolutionScene = 15,
    SelectUnitScene = 16,
    UnitUpResultScene = 17,
    ShopScene = 18,
    RankingScene = 19,
    MailBoxScene = 20,
    GameEnterRoomScene = 3,
    GamePvPRoomWaitting = 4,
    PvPMakeRoomScene = 22,
    PVP_MakeRoomScene21 = 21,
    GameReadyScene = 23,
    InGameScene = 99,
    GoToStageScene = 5,
}

public class CSceneManager : MonoBehaviour
{

    public static string StageElement = "Random";

    public static bool NowNetworkSwitching = false;

	public static int BuilderCMDBtnWidth = (Screen.width > Screen.height ? Screen.width : Screen.height) / 10;
	public static int BuilderCMDBtnHeight = (Screen.width < Screen.height ? Screen.width : Screen.height) / 10;

    public static string Version = "Now Checking...";

	public static string WEB_SERVER_URL
	{
		get
		{
			if( CSceneManager.BuildType == 1 )
				return "http://172.20.80.193:8080/dice_deploy";
			else if( CSceneManager.BuildType == 0 )
				return "http://172.20.80.159:8080/dice_deploy";
			else if( CSceneManager.BuildType == 2 )
				return  "http://" + PlayerPrefs.GetString("CustomGameServerAddress") + ":8080/dice_deploy";
			else
				return "http://172.20.80.159:8080/dice_deploy";
		}
	}
	
	public static string WEB_DOWNLOAD_URL
	{
		get
		{
			if( CSceneManager.BuildType == 1 )
				return "http://172.20.80.193:8080/res";
			else if( CSceneManager.BuildType == 0 )
				return "http://172.20.80.159:8080/res";
			else if( CSceneManager.BuildType == 2 )
				return  "http://" + PlayerPrefs.GetString("CustomGameServerAddress") + ":8080/res";
			else
				return "http://172.20.80.159:8080/res";
		}
	}
	
	public static int BuildType = 0;

	float buttonSizeMultipier = 1.0f;

	public static int widthScreen = 1280;
	public static int heightScreen = 720;

	public TextAsset msgTextAsset;
	public string [] msgText;
	public int testCharID;
	public element testThemeType;
    public static SCENE m_Scene = SCENE.LoadingScene;
    private static SCENE m_prevSceneIndex = SCENE.LoadingScene;
    public static SCENE prevSceneIndex
	{
		get { return m_prevSceneIndex; } 
		set {m_prevSceneIndex = value; }
	}

    public static int ServerType = 0;

	public static string m_mapName;
	public static element m_themeType;
    public static bool SceneManagerCreated = false;
	public static bool isPopupDisconnectMsgBox = false;
    public static bool isPopupWarnningMsgBox = false;

	public static bool LoginSuccess = false;
	public static bool VersionCheckSuccess = false;
	public static bool LoadUserDataFromWeb = false;
	public static bool LoadDoneFromWebServer = false;

	public static bool BuilderIsOn = false;
	public static bool BOTIsOn = false;
	public static bool isSingleGame = false;
	public static bool hideDebugUI = false;
	private int firstDice = 0;
	private int secondDice = 0;
	public static int charSelected = 2;
	public static bool isReplay;
	public static bool isIngameTutorial;
	public static bool bTestBossAnimation;
	//public static bool isSaveReplay;
	
    bool m_bInit = false;
    int m_nTick = 0;
	public static int BuilderStatus = 0;
	
	public static CSceneManager manager;

	public List<string> SkillList = new List<string>();
    public List<string> TempSkillList = new List<string>();
	public static int Skill_1_Index = 0;
	public static int Skill_2_Index = 0;
	public static int SkillIndex = 0;
    public static int TempSkillIndex = 0;
	public static bool bShowPacketWaitingInfo;
	public static GameStatus gameStatus;

    void Awake()
    {
        //testThemeType = element.sky;
        SkillList.Clear();
        SkillList.Add("player_resurrect_01");
        SkillList.Add("player_card_actvate_01");
        SkillList.Add("player_heal_hp_05");
        SkillList.Add("player_card_element_change_good_01");
        SkillList.Add("player_send_card_to_tomb_01");
        SkillList.Add("player_card_activate_random_all_01");
        SkillList.Add("player_block_01");
        SkillList.Add("player_avoid_01");
        SkillList.Add("player_avoid_02_move_06");
        SkillList.Add("player_install_trap_decoy_01");
        SkillList.Add("player_teleport_to_random_player_01");
        SkillList.Add("player_tile_frozen_01");
        SkillList.Add("player_chase_03_berserk");
        
        SkillList.Add("player_confuse_moveback_01");
        SkillList.Add("player_confuse_bind_01");
        SkillList.Add("player_confuse_sleep_01");

        SkillList.Add("player_moveback_01");
        SkillList.Add("player_block_02");
        SkillList.Add("player_confuse_moverandom_01");
        SkillList.Add("player_tile_ignore_01");
        SkillList.Add("player_bumpy_01");
        SkillList.Add("player_seal_active_card_slot");
        SkillList.Add("player_damage_shield_01");
        SkillList.Add("player_get_treasure_01");
        SkillList.Add("player_transfer_move");
        SkillList.Add("player_transfer_attack");
        SkillList.Add("player_transfer_defense");
        SkillList.Add("player_mp_burn");
        SkillList.Add("player_card_element_change_bad");
        SkillList.Add("player_abnormal_delete_bad_01");
        SkillList.Add("player_abnormal_delete_good_01");
        SkillList.Add("player_help_from_other_element");
        SkillList.Add("player_pushback_resist_03");
        SkillList.Add("player_way_select_01");


        TempSkillList.Clear();
        TempSkillList.Add("chance_card_mp_recover_01");
        TempSkillList.Add("chance_card_mp_recover_02");
        TempSkillList.Add("chance_card_mp_recover_03");
        TempSkillList.Add("chance_card_mp_recover_04");
        TempSkillList.Add("chance_card_resurrect_04");
        TempSkillList.Add("chance_card_hp_recover_04");

#if !UNITY_EDITOR
        glog.debug(LTreeBinding.GetBuildType());
        if (LTreeBinding.GetBuildType().Equals("QA"))
		{
			CSceneManager.BuildType = 1;
		}
        else if (LTreeBinding.GetBuildType().Equals("DEV"))
        {
            CSceneManager.BuildType = 0;
        }
#endif
		if( !string.IsNullOrEmpty(PlayerPrefs.GetString("CustomGameServerAddress")) )
		{
			Debug.LogError("CUSTOM SERVER!!!");
			CSceneManager.BuildType = 2;
		}

        if (SceneManagerCreated)
        {
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
			manager = this;
			gameObject.AddComponent<glog>();
            SceneManagerCreated = true;

            //CNetworkManager.Instance.Method = EventHandlerForStageManagerWrapper;
            //CNetworkManager.Instance.PacketHandler = LoadingSceneManager.PacketHandler;
//#if UNITY_EDITOR
//            CNetworkManager.Instance.Log = PrintLog;
//#endif
            m_bInit = true;
        }
		buttonSizeMultipier = (float)Screen.width / 800.0f;
		
		Screen.autorotateToLandscapeLeft = true;
		Screen.autorotateToLandscapeRight = true;
		Screen.autorotateToPortrait = false;
		Screen.autorotateToPortraitUpsideDown = false;
		Screen.orientation = ScreenOrientation.AutoRotation;

		Screen.sleepTimeout = SleepTimeout.NeverSleep;
    }

    static bool PrintLog(string msg)
    {
#if UNITY_EDITOR
        glog.debug("Log:" + msg);
#endif
        return true;
    }

    static bool EventHandlerForStageManagerWrapper(DICE_GS.LogType type, string msg)
    {
        ;
        return false;
    }

    void Start()
    {
        //string[,] grid = CSVReader.SplitCsvGrid(msgTextAsset.text);
        //glog.debug ("msgTextasset line length="+grid.GetUpperBound(1));
        //msgText = new string[grid.GetUpperBound(1)];
        //for (int y = 0; y<grid.GetUpperBound(1) ; y++) {
        //    msgText[y] = grid[0,y];
        //}

        //CNetworkManager.Instance.Method = EventHandlerForStageManagerWrapper;
        //CNetworkManager.Instance.PacketHandler = LoadingSceneManager.PacketHandler;
#if UNITY_EDITOR
        CNetworkManager.Instance.Log = PrintLog;
#endif

        //CNetworkManager.Instance.ConnectToServer();

        //StartDownloadResouces();
		SoundManagerCommon.Instance.PlayBGM(2);

        //Application.RegisterLogCallback(LogHandler);
    }

	void ClearNotificationBadge()
	{
#if UNITY_IPHONE
		LocalNotification setCountNotif = new LocalNotification();
		setCountNotif.fireDate = System.DateTime.Now;
		setCountNotif.applicationIconBadgeNumber = -1;
		setCountNotif.hasAction = false;
		NotificationServices.ScheduleLocalNotification( setCountNotif );
#endif
	}

	string _logString;
	string _stackTrace;
	void LogHandler(string logString, string stackTrace, UnityEngine.LogType type)
	{
		if( type == UnityEngine.LogType.Exception || type == UnityEngine.LogType.Assert )
		{
			_logString = logString;
			_stackTrace = stackTrace;
			string fileContents = logString + "\n\n" + stackTrace;
			string fileName = string.Format("CrashReport_{0}_{1}_{2}_{3}_{4}_{5}_{6}_{7}_{8}.txt", MyInfo.Instance.DBID, MyInfo.Instance.NickName, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
			string FN = string.Format("{0}/{1}", SystemCore.GetAssetPath(), fileName);
			LCFileManager.FileWriteAllText(FN, fileContents);

			string[] param = new string[2];
			Debug.Log("1");
			param[0] = logString;
			Debug.Log("1");
			param[1] = stackTrace;
			Debug.Log("1");
			MessagePopup.window.ShowPopup(MESSAGEPOPUPTYPE.ClientCrashorException, param, null);
			Debug.Log("1");
		}
	}

//	public void MessagePopupCallback(MESSAGEPOPUPTYPE type, bool isYes)
//	{
//			string fileContents = _logString + "\n\n" + _stackTrace;
//			string fileName = string.Format("CrashReport_{1}_{2}_{3}_{4}_{5}_{6}_{7}.txt", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
//			string FN = string.Format("{0}/{1}", SystemCore.GetAssetPath(), fileName);
//			LCFileManager.FileWriteAllText(FN, fileContents);
//
//	}

    public void StartDownloadResouces()
    {
        StartCoroutine("DownloadResources");
    }

	IEnumerator FadeToNextLevel(string levelName)
	{
//		LoadingWindow.window.HideLoading();
		//GameObject go = Instantiate(FadeOutPrefab) as GameObject;
		//DontDestroyOnLoad(go);
		//yield return new WaitForSeconds(0.09f);
        TopInfoBar.Instance.SetBarBeforeLevelLoad();
        PopupManager.SetPopupBeforeLevelLoad();
		Resources.UnloadUnusedAssets();
		Application.LoadLevelAsync(levelName);
		//yield return new WaitForSeconds(0.001f);
		//Destroy(go);
		yield return null;
	}
	
    public void GoToLoadingScene()
    {
		if(isReplay)
			return;
		
		StageManagerWrapper.ClearStage();
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.LoadingScene;
        LoadUserDataFromWeb = false;
        LoadDoneFromWebServer = false;
        glog.debug("GoToLoadingScene()");
        CNetworkManager.Instance.PacketHandler = LoadingSceneManager.PacketHandler;
//		LoadingSceneManager.isForcedReLogin = true;
        Application.LoadLevel("02_UI_AutoLogin");
    }

    public void GotoInputNicknameScene()
    {
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.CharacterSelectScene;
        StartCoroutine(FadeToNextLevel("05_UI_CharSelect") );
		CNetworkManager.Instance.PacketHandler = CharacterSelectSceneManager.PacketHandler;
    }
    
    public void GoToWaitroomScene()
    {
		if(!isReplay)
		{
			m_prevSceneIndex = m_Scene;
            m_Scene = SCENE.MainScene;
	        glog.debug("GoToWaitroomScene()");
	        CNetworkManager.Instance.PacketHandler = WaitingRoomSceneManager.PacketHandler;
//	        StartCoroutine(FadeToNextLevel("06_UI_WaitingRoom") );
            if (m_prevSceneIndex == SCENE.InGameScene)
			{
				Resources.UnloadUnusedAssets();
				AutoFade.LoadLevel("06_UI_Main", 0.5f, 1.0f, Color.black);
			}
			else
			{
				if( prevSceneIndex != m_Scene )
					StartCoroutine(FadeToNextLevel("06_UI_Main") );
			}
		}
        
    }

	public void GoToEnterroomScene(string map, string friendName)
	{
        LoadingWindow.window.ShowShortLoading();
		if(isReplay)
		{
			m_mapName = "map_" + map.ToString();
			System.GC.Collect();
			System.GC.WaitForPendingFinalizers();
			Resources.UnloadUnusedAssets();
			Application.LoadLevel("BoardMap");
		}
		else
		{
			if(isSingleGame)
			{
                //if (CNetworkManager.Instance.Connected)
                //{
                //    PC_OP_JOIN packet = new PC_OP_JOIN();
					
                //    packet.JoinType = (byte)JoinType.JT_TEST;
                //    packet.RoomName = SystemInfo.deviceUniqueIdentifier;
                //    m_mapName = "map_" + map.ToString();
                //    packet.MapName = m_mapName;
                //    packet.FriendName = friendName;
                //    //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
                //    CNetworkManager.Instance.SendPacket(packet);
                //}		
                //m_mapName = "map_" + map.ToString();

                CPVEStageData tmpData = CPVEStageDataManager.Instance.GetPVEStageData(1);

                RequestJoinToMaster(JoinType.JT_SINGLE_JOIN, "", "map_" + tmpData.map_name, friendName, tmpData.id);
			}
			else
			{
				m_prevSceneIndex = m_Scene;
                m_Scene = SCENE.GameEnterRoomScene;
				m_mapName = "map_" + map.ToString();
				glog.debug("GoToEnterroomScene()");
				CNetworkManager.Instance.PacketHandler = EnterRoomSceneManager.PacketHandler;
				StartCoroutine(FadeToNextLevel("07_UI_EnterRoom") );
			}
		}
	}

    public void GoToEnterroomScene(MapList map)
    {
        LoadingWindow.window.ShowShortLoading();
		if(isReplay)
		{
			m_mapName = "map_" + map.ToString();
			Application.LoadLevel("BoardMap");
		}
		else
		{
			if(isSingleGame)
			{
                //if (CNetworkManager.Instance.Connected)
                //{
                //    PC_OP_JOIN packet = new PC_OP_JOIN();
		
                //    packet.JoinType = (byte)JoinType.JT_TEST;
                //    packet.RoomName = SystemInfo.deviceUniqueIdentifier;
                //    m_mapName = "map_" + map.ToString();
                //    packet.MapName = m_mapName;
                //    //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
                //    CNetworkManager.Instance.SendPacket(packet);
                //}		

                CPVEStageData tmpData = CPVEStageDataManager.Instance.GetPVEStageData(1);

                RequestJoinToMaster(JoinType.JT_SINGLE_JOIN, "", "map_" + tmpData.map_name, "", tmpData.id);

			}
			else
			{
				m_prevSceneIndex = m_Scene;
                m_Scene = SCENE.GameEnterRoomScene;
				m_mapName = "map_" + map.ToString();
		        glog.debug("GoToEnterroomScene()");
		        CNetworkManager.Instance.PacketHandler = EnterRoomSceneManager.PacketHandler;
		        StartCoroutine(FadeToNextLevel("07_UI_EnterRoom") );
			}
		}
    }

    public void GoToPvpRoomWaitingScene()
    {
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.GamePvPRoomWaitting;
        glog.debug("GoToPvpRoomWaitingScene()");
        CNetworkManager.Instance.PacketHandler = RoomWaitingSceneManager.PacketHandler;
        StartCoroutine(FadeToNextLevel("08_UI_PvP_RoomWaiting") );
        
    }

    public void GoToStageScene()
    {
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.GoToStageScene;
        glog.debug("GoToStageScene()");
        CNetworkManager.Instance.PacketHandler = StageManagerWrapper.PacketHandler;
        //StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");

		LoadStageLevel("BoardMap");
    }

	public void GoToDeckEditScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.DeckEditScene;
		glog.debug("GoToDeckEditScene()");
		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("06_UIn_Team"));
	}

	public void GoToUnitInvenScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.UnitInvenScene;

		glog.debug("GoToUnitInvenScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("06_UIn_Team2_new"));
	}

	public void GoToUnitChangeConfirmScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.UnitChangeConfirmScene;

		glog.debug("GoToUnitChangeConfirmScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("06_UIn_Team3"));
	}
	
	public void GoToSummonMenuScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.SummonMenuScene;

		glog.debug("GoToSummonMenuScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("10_UI_summons1_menu"));
	}
	
	public void GoToSummonCommonScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.SummonCommonScene;

		glog.debug("GoToSummonCommonScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("10_UI_summons2_common"));
	}
	
	public void GoToSummonRareScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.SummonRareScene;

		glog.debug("GoToSummonRareScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("10_UI_summons2_rare"));
	}
	
	public void GoToSummonResultScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.SummonResultScene;

		glog.debug("GoToSummonResultScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("10_UI_summons3_result"));
	}
	
	public void GoToUnitMenuScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.UnitMenuScene;

		glog.debug("GoToUnitMenuScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("11_UI_card_menu_temp"));
	}
	
	public void GoToUnitLevelUpScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.UnitLevelupScene;

		glog.debug("GoToUnitLevelUpScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine((FadeToNextLevel(m_mapName) );
		//Application.LoFadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("12_UI_CardLevelUp"));
	}
	
	public void GoToUnitPowerUpScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.UnitEvolutionScene;

		glog.debug("GoToUnitPowerUpScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("14_UI_evolution1_menu"));
	}
	
	public void GoToSelectUnitScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.SelectUnitScene;

		glog.debug("GoToSelectUnitScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("13_UI_select2_multi"));
	}
	
	public void GoToUnitUpResultScene()
	{
		m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.UnitUpResultScene;

		glog.debug("GoToUnitUpResultScene()");
//		CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
		//StartCoroutine(FadeToNextLevel(m_mapName) );
		//Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("15_UI_card_result"));
	}

    public void GoToShopScene()
    {
        m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.ShopScene;

        glog.debug("GoToShopScene()");
//        CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
        //StartCoroutine(FadeToNextLevel(m_mapName) );
        //Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("17_UI_Shop_main_new"));
	}

    public void GoToRankingScene()
    {
        m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.RankingScene;

        glog.debug("GoToRankingScene()");
//        CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
        //StartCoroutine(FadeToNextLevel(m_mapName) );
        //Application.LoadLevel("BoardMap");
        StartCoroutine(FadeToNextLevel("16_UI_ranking1"));
    }

    public void GoToSocialMenuScene()
    {
        m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.MailBoxScene;
		
		MyInfo.Instance.MyMailboxList.Clear();

        glog.debug("GoToSocialMenuScene()");
//        CNetworkManager.Instance.PacketHandler = DeckEditSceneManager.PacketHandler;
        //StartCoroutine(FadeToNextLevel(m_mapName) );
        //Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("19_UI_mailbox_temp"));
    }
	
	public void GoToPvPDirectEnterRoomScene()
    {
        m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.PVP_MakeRoomScene21;

        glog.debug("GoToPvPDirectEnterRoomScene()");
        CNetworkManager.Instance.PacketHandler = PvPMakeRoomSceneManager.PacketHandler;
        //StartCoroutine(FadeToNextLevel(m_mapName) );
        //Application.LoadLevel("BoardMap");
        StartCoroutine(FadeToNextLevel("07_UI_PVP_MakeRoom"));
    }
	
	public void GoToPvPCreateEnterRoomScene()
    {
        m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.PvPMakeRoomScene;

        glog.debug("GoToPvPCreateEnterRoomScene()");
        CNetworkManager.Instance.PacketHandler = PvPMakeRoomSceneManager.PacketHandler;
        //StartCoroutine(FadeToNextLevel(m_mapName) );
        //Application.LoadLevel("BoardMap");
        StartCoroutine(FadeToNextLevel("07_UI_PVP_MakeRoom"));
    }
	
	public void GoToGameReadyScene()
    {
        m_prevSceneIndex = m_Scene;
        m_Scene = SCENE.PvPMakeRoomScene;
		
        glog.debug("GoToGameReadyScene()");
//        CNetworkManager.Instance.PacketHandler = PvPMakeRoomSceneManager.PacketHandler;
        //StartCoroutine(FadeToNextLevel(m_mapName) );
        //Application.LoadLevel("BoardMap");
		StartCoroutine(FadeToNextLevel("07_UI_PVP_MakeRoom"));
    }

	public void LoadStageLevel(string name){
        m_Scene = SCENE.InGameScene;
	   // iGUILoadingHelper.showLoading(iGUILoading.Both, 0.3f);   
		System.GC.Collect();
		System.GC.WaitForPendingFinalizers();
		Resources.UnloadUnusedAssets();
		AutoFade.LoadLevel(name, 0.5f, 0.5f, Color.black);
		
		
//	    AsyncOperation async = Application.LoadLevelAsync(name);
//	    StartCoroutine(LoadLevelAsync(async));
	}	
	
	IEnumerator LoadLevelAsync(AsyncOperation async){           
	    while(!async.isDone){
			//iGUILoadingHelper.progress = async.progress;  
	        glog.debug("loading.."+async.progress);
	        yield return null;
	    }
	   // iGUILoadingHelper.hideLoading();
		glog.debug("Loading complete");
	}	

	public static void DisableMinimapCollider(bool bDisable)
	{
		UIRoot root = GameObject.Find ("UI Root (2D)").GetComponent<UIRoot>();
		if(root!=null)
		{
			Camera cam = root.GetComponentInChildren<Camera>();
			if(cam!=null)
			{
				UIAnchor anchor = cam.gameObject.GetComponentInChildren<UIAnchor>();
				if(anchor!=null)
				{
					Transform t = anchor.gameObject.transform.FindChild("MainUIPanel");
					if(t!=null)
					{
						t = t.FindChild("Top");
						if(t!=null)
						{
							t = t.FindChild("MiniMap");
							if(t!=null)
							{
								glog.debug("Minimap collider disable="+bDisable);
								t.gameObject.GetComponent<BoxCollider>().enabled = !bDisable;
							}
						}
					}
				}
			}
		}
	}
	
	public static GameObject FindDebugPanel()
	{
    	UIRoot root = GameObject.Find ("UI Root (2D)").GetComponent<UIRoot>();
    	if(root!=null)
    	{
    		Camera cam = root.GetComponentInChildren<Camera>();
    		if(cam!=null)
    		{
	    		UIAnchor anchor = cam.gameObject.GetComponentInChildren<UIAnchor>();
	    		if(anchor!=null)
	    		{
					Transform t = anchor.gameObject.transform.FindChild("DebugPanel");
					if(t==null)
						t = anchor.gameObject.transform.FindChild("DebugPanel(Clone)");
					if( t!=null)
						return t.gameObject;
					else
					{
						if(m_Scene == SCENE.InGameScene || isReplay)
						{
							glog.debug("create debug panel");
							return NGUITools.AddChild (anchor.gameObject, Resources.Load("Prefabs/Ingame/DebugPanel") as GameObject );
						}
						return null;
					}
				}
			}
		}
		return null;
	}
	
	public static void ShowDebugPanel(bool bActive)
	{
		GameObject go = FindDebugPanel();
		if(go!=null)
		{
			go.SetActive(bActive);
		}
	}
	public static void ToggleDebugPanel()
	{
		GameObject go = FindDebugPanel();
		if(go!=null)
		{
			if(go.activeSelf)
				go.SetActive(false);
			else
			{
				go.SetActive(true);
				Transform serverOnTrans = go.transform.FindChild("serverOn");
				if(serverOnTrans!=null)
				{
					GameObject serverOnGo = serverOnTrans.gameObject;
					if(BuilderIsOn)
					{
						serverOnGo.GetComponent<UISprite>().color = new Color(53.0f/255, 1,1);
						serverOnGo.GetComponentInChildren<UILabel>().text = "Off";
					}
					else
					{
						serverOnGo.GetComponent<UISprite>().color = new Color(1,1,1);
						serverOnGo.GetComponentInChildren<UILabel>().text = "On";
					}

					GameObject packetWaitingGo = go.transform.FindChild("packetInfo").gameObject;
					if(bShowPacketWaitingInfo)
					{
						packetWaitingGo.GetComponent<UISprite>().color = new Color(53.0f/255, 1,1);
					}
					else
					{
						packetWaitingGo.GetComponent<UISprite>().color = new Color(1, 1,1);
					}
					go.transform.FindChild("curTurn").gameObject.GetComponent<UILabel>().text = StageManagerWrapper.manager.m_curTurn.ToString();
				}
			}
		}
	}	
	
	public void SetCharSelect(int nSelect)
	{
		charSelected = nSelect;
		MyInfo.Instance.pawnId = charSelected;
        LoadingWindow.window.ShowShortLoading();
		RestAPI.singleton.PutUserData(ReturnCallback);		
	}

	bool tokenSent = false;
    // Update is called once per frame
    void FixedUpdate()
    {
        try
        {
           	CNetworkManager.Instance.Update();

#if UNITY_IPHONE
			if( !tokenSent )
			{
				byte[] token = NotificationServices.deviceToken;
				if( token != null )
				{
					string tokenString = System.BitConverter.ToString(token).Replace("-", "").ToLower();
					if( tokenString.Equals(PlayerPrefs.GetString("pushToken")) )
					{
						RestAPI.singleton.SendDevicePushToken(ReturnCallback, tokenString);
						tokenSent = true;
						Debug.LogError("OnTokenReceived : " + tokenString);
					}
				}
			}
#endif
        }
        catch (Exception e)
        {
            glog.debug(e.ToString());
        }		
    }

	void Update()
	{
		if( Input.GetKeyDown( KeyCode.Escape) )
		{
			Debug.LogError("back key down");
		}
	}

	public static void SendVersionPacket()
	{
        PC_CS_CHECK_VERSION packet = new PC_CS_CHECK_VERSION();

		packet.AssetVersion = "";
		
		string[] a =  System.Reflection.Assembly.GetAssembly(packet.GetType()).FullName.Split(' ');

		foreach (string s in a)
		{
			if(s.Trim().StartsWith("Version"))
			{
				CSceneManager.Version = s.Split('=', ',')[1];
				break;
			}
		}
        packet.GameLogicVersion = CSceneManager.Version;
		
		//CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
		CNetworkManager.Instance.SendPacket(packet);
	}

	public static void SendLoginPacket()
	{
		LoginSuccess = false;

        PC_CS_LOGIN packet = new PC_CS_LOGIN();

		packet.DeviceKey = SystemInfo.deviceUniqueIdentifier;
		
		Debug.Log(packet.DeviceKey);

		if (FB.UserId != null)
		{
			packet.SocialKey = FB.AccessToken;
			packet.SocialID = FB.UserId;
		}

        if (m_Scene == SCENE.LoadingScene || m_Scene == SCENE.CharacterSelectScene)
        {
            packet.LoginType = (int)LoginType.TO_STAMP;
        }

		//CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
		CNetworkManager.Instance.SendPacket(packet);
	}

    //public void OnTestJoinButton(string mapname)
    //{
    //    LoadingWindow.window.ShowShortLoading();
    //    if (CNetworkManager.Instance.Connected)
    //    {
    //        PC_OP_JOIN packet = new PC_OP_JOIN();

    //        packet.JoinType = (byte)JoinType.JT_TEST;
    //        packet.RoomName = SystemInfo.deviceUniqueIdentifier;
    //        m_mapName = mapname;
    //        packet.MapName = m_mapName;
    //        //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
    //        CNetworkManager.Instance.SendPacket(packet);
    //    }
    //}

    public void OnRandomJoinButton()
    {
        LoadingWindow.window.ShowShortLoading();
        //if (CNetworkManager.Instance.Connected)
        //{
        //    PC_OP_JOIN packet = new PC_OP_JOIN();

        //    packet.JoinType = (byte)JoinType.JT_RANDOM;
        //    packet.RoomName = SystemInfo.deviceUniqueIdentifier;
        //    glog.debug ("mapname="+m_mapName);
        //    packet.MapName = m_mapName;

        //    //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
        //    CNetworkManager.Instance.SendPacket(packet);
        //}
        RequestJoinToMaster(JoinType.JT_RANDOM_JOIN, "", m_mapName, "");
    }


    public void OnCreateJoinButton()
    {
        LoadingWindow.window.ShowShortLoading();
        //if (CNetworkManager.Instance.Connected)
        //{
        //    PC_OP_JOIN packet = new PC_OP_JOIN();

        //    packet.JoinType = (byte)JoinType.JT_CREATE;
        //    packet.RoomName = SystemInfo.deviceUniqueIdentifier;
        //    glog.debug ("mapname="+m_mapName);
        //    packet.MapName = m_mapName;
        //    //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
        //    CNetworkManager.Instance.SendPacket(packet);
        //}
        
        RequestJoinToMaster(JoinType.JT_CREATE_JOIN, "", m_mapName, "");
    }


    public void LeaveRoom()
    {
		if (CNetworkManager.Instance.Connected)
        {
            PC_OP_LEAVE packet = new PC_OP_LEAVE();

            //CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
            //CNetworkManager.Instance.SendPacket(packet);
            CNetworkManager.Instance.m_PhotonPeer.OpLeave();
        }
    }

	public static bool DataLoaded { get; set; }

	public void RequestDeckInfo()
	{
		StartCoroutine("RequestDeckInfoToWeb");
	}

	IEnumerator RequestDeckInfoToWeb()
	{
		WWW www = new WWW(CSceneManager.WEB_SERVER_URL + "/api/deck?UserId=" + MyInfo.Instance.DBID);
        yield return www;

		if (www.error == null)
		{
			JsonData data = JsonMapper.ToObject(www.text);

			Debug.LogError(www.text); /* {"Id":2,"UserId":2,"Leader":1,"Sub1":2,"Sub2":3,"Sub3":4,"Sub4":5} */

			MyInfo.Instance.MyDeckMap.Clear();

			DeckInfo tmpDeckInfo = new DeckInfo();

			int SlotUID = (int)data["Id"];
			int UserDBID = (int) data["UserId"];

			if(UserDBID == MyInfo.Instance.DBID)
			{
				MyInfo.Instance.MyCurrentDeckDBID = SlotUID;
				if(data["Leader"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Leader"], 0, 0);
					tmpDeckInfo.AddUnitInfo(0, tmpUnit);
				}

				if(data["Sub1"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Sub1"], 0, 0);
					tmpDeckInfo.AddUnitInfo(1, tmpUnit);
				}

				if(data["Sub2"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Sub2"], 0, 0);
					tmpDeckInfo.AddUnitInfo(2, tmpUnit);
				}

				if(data["Sub3"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Sub3"], 0, 0);
					tmpDeckInfo.AddUnitInfo(3, tmpUnit);
				}

				if(data["Sub4"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Sub4"], 0, 0);
					tmpDeckInfo.AddUnitInfo(4, tmpUnit);
				}

				MyInfo.Instance.MyDeckMap.Add(0, tmpDeckInfo);

				RequestMyUnitListInfo();
			}
		}
		else
		{
			glog.debug(www.error);
		}
	}



	internal void RefrechDeckInfo()
	{
		StartCoroutine("RefreshDeckInfoToWeb");
	}

	IEnumerator RefreshDeckInfoToWeb()
	{
		WWW www = new WWW(CSceneManager.WEB_SERVER_URL + "/api/deck?UserId=" + MyInfo.Instance.DBID);
		yield return www;

		if (www.error == null)
		{
			MyInfo.Instance.MyDeckMap.Clear();

			JsonData data = JsonMapper.ToObject(www.text);

			Debug.LogError(www.text); /* {"Id":2,"UserId":2,"Leader":1,"Sub1":2,"Sub2":3,"Sub3":4,"Sub4":5} */

			DeckInfo tmpDeckInfo = new DeckInfo();

			int SlotUID = (int)data["Id"];
			int UserDBID = (int)data["UserId"];

			if (UserDBID == MyInfo.Instance.DBID)
			{
				MyInfo.Instance.MyCurrentDeckDBID = SlotUID;
				if (data["Leader"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Leader"], 0, 0);
					tmpDeckInfo.AddUnitInfo(0, tmpUnit);
				}

				if (data["Sub1"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Sub1"], 0, 0);
					tmpDeckInfo.AddUnitInfo(1, tmpUnit);
				}

				if (data["Sub2"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Sub2"], 0, 0);
					tmpDeckInfo.AddUnitInfo(2, tmpUnit);
				}

				if (data["Sub3"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Sub3"], 0, 0);
					tmpDeckInfo.AddUnitInfo(3, tmpUnit);
				}

				if (data["Sub4"] != null)
				{
					UnitInfo tmpUnit = new UnitInfo((int)data["Sub4"], 0, 0);
					tmpDeckInfo.AddUnitInfo(4, tmpUnit);
				}

				MyInfo.Instance.MyDeckMap.Add(0, tmpDeckInfo);

				RequestMyUnitListInfo();
			}
		}
		else
		{
			glog.debug(www.error);
		}
	}
	
	public void RequestMyUnitListInfo()
	{
		StartCoroutine("RequestMyUnitListInfoToWeb");
	}

	IEnumerator RequestMyUnitListInfoToWeb()
	{
		WWW www = new WWW(CSceneManager.WEB_SERVER_URL + "/api/unit?UserId=" + MyInfo.Instance.DBID);
        yield return www;

		if (www.error == null)
		{
			JsonData data = JsonMapper.ToObject(www.text);

			Debug.LogError(www.text); /* {"Id":2,"UserId":2,"Leader":1,"Sub1":2,"Sub2":3,"Sub3":4,"Sub4":5} */

			MyInfo.Instance.MyUnitsList.Clear();

			//temporary, must be modified. By HyunSeung(13.09.26)
			for(int i=0; i<data.Count; i++)
			{
				int dbId = int.Parse(data[i]["Id"].ToString());
				int classId = int.Parse(data[i]["UnitId"].ToString());
				int exp = int.Parse(data[i]["Exp"].ToString());
                int level = int.Parse(data[i]["Level"].ToString());
                int grade = int.Parse(data[i]["Grade"].ToString());
				MyInfo.Instance.MyUnitsList.Add(new UnitInfo(dbId, classId, level, exp, grade));
			}

			CSceneManager.LoadDoneFromWebServer = true;
		}
		else
		{
			glog.debug(www.error);
		}
	}

	internal void SubmitUnitChange()
	{
		StartCoroutine("SubmitUnitChangeToWeb");
	}

	IEnumerator SubmitUnitChangeToWeb()
	{

		WWWForm form = new WWWForm();

		form.AddField("Id", MyInfo.Instance.MyCurrentDeckDBID);
		form.AddField("UserId", MyInfo.Instance.DBID);

		if (MyInfo.Instance.LastSeletedUnitSlot == 0)
		{
			form.AddField("Leader", MyInfo.Instance.LastSelectedUnitDBID);
		}
		else
		{
			form.AddField("Leader", MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].SlotMap[0].UnitDBID);
		}

		if (MyInfo.Instance.LastSeletedUnitSlot == 1)
		{
			form.AddField("Sub1", MyInfo.Instance.LastSelectedUnitDBID);
		}
		else
		{
			form.AddField("Sub1", MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].SlotMap[1].UnitDBID);
		}

		if (MyInfo.Instance.LastSeletedUnitSlot == 2)
		{
			form.AddField("Sub2", MyInfo.Instance.LastSelectedUnitDBID);
		}
		else
		{
			form.AddField("Sub2", MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].SlotMap[2].UnitDBID);
		}

		if (MyInfo.Instance.LastSeletedUnitSlot == 3)
		{
			form.AddField("Sub3", MyInfo.Instance.LastSelectedUnitDBID);
		}
		else
		{
			form.AddField("Sub3", MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].SlotMap[3].UnitDBID);
		}

		if (MyInfo.Instance.LastSeletedUnitSlot == 4)
		{
			form.AddField("Sub4", MyInfo.Instance.LastSelectedUnitDBID);
		}
		else
		{
			form.AddField("Sub4", MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].SlotMap[4].UnitDBID);
		}

		WWW www = new WWW(CSceneManager.WEB_SERVER_URL + "/api/deck", form);
		yield return www;

		if (www.error == null)
		{
			//StartCoroutine("RefreshDeckInfoToWeb");
			CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
			c.RefrechDeckInfo();
		}
		else
		{
			glog.debug(www.url);
			glog.debug("Post!!!!!!!!!!!!! Error");
			glog.debug(www.error);
		}
		
	}


	private int addedUnit = 0;
	
	public static void ContinuePlay()
	{
		PC_OP_CONTINUE_PLAY packet = new PC_OP_CONTINUE_PLAY();
		packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
		//CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
		CNetworkManager.Instance.SendPacket(packet);		
	}
	
	public void SaveReplay()
	{
		if(!isReplay)
			StageManagerWrapper.SaveReplay(false);
	}

	public void SendGiveUp()
	{
		PC_CS_GIVE_UP_GAME packet = new PC_CS_GIVE_UP_GAME();
		packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
		
		CNetworkManager.Instance.SendPacket(packet);
	}

	public void SendGetRandomBoxInfos()
	{
		PC_CS_REQUEST_RANDOM_BOX packet = new PC_CS_REQUEST_RANDOM_BOX();
		packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
		
		CNetworkManager.Instance.SendPacket(packet);
	}

	public void SendSelectRandomBox(int selectedBoxIndex)
	{
		PC_CS_SELECT_RANDOM_BOX packet = new PC_CS_SELECT_RANDOM_BOX();
		packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
		byte[] temp = new byte[1];
		temp[0] = (byte)selectedBoxIndex;
		packet.SelectSlot = temp;
		packet.SelectCount = (byte)temp.Length;
		
		CNetworkManager.Instance.SendPacket(packet);
		Debug.LogError("SendSelectRandomBox");
	}

	public void SendSelectRandomBox(List<int> selectedBoxIndex)
	{
		PC_CS_SELECT_RANDOM_BOX packet = new PC_CS_SELECT_RANDOM_BOX();
		packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
		byte[] temp = new byte[selectedBoxIndex.Count];
		for(int i=0; i<selectedBoxIndex.Count; i++)
		{
			temp[i] = (byte)selectedBoxIndex[i];
			Debug.LogError(temp.ToString());
		}
		packet.SelectSlot = temp;
		packet.SelectCount = (byte)temp.Length;
		
		CNetworkManager.Instance.SendPacket(packet);
		Debug.LogError("SendSelectRandomBox");
	}

	public void SendBuyOneMoreRandomBox(int selectedBoxIndex)
	{
		PC_CS_BUY_RANDOM_BOX packet = new PC_CS_BUY_RANDOM_BOX();
		packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
		packet.SelectSlot = (byte)selectedBoxIndex;
		
		CNetworkManager.Instance.SendPacket(packet);
	}

	public void SendEmoticonChat(int id)
	{
		PC_OP_EMOTION_CHAT packet = new PC_OP_EMOTION_CHAT();
		
		packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
		packet.Message = id.ToString();
		
		CNetworkManager.Instance.SendPacket(packet);
	}

	public static bool IsIngameScene()
	{
		if(m_Scene == SCENE.InGameScene || isReplay)
			return true;
		return false;
	}
	
	void OnGUI()
	{

		BuilderCMDBtnWidth = (Screen.width > Screen.height ? Screen.width : Screen.height) / 10;
		BuilderCMDBtnHeight = (Screen.width < Screen.height ? Screen.width : Screen.height) / 10;

		#region Builder Command
		if (m_Scene == SCENE.InGameScene || isReplay)
		{
			if (GUI.Button(  new Rect(Screen.width - 60 * buttonSizeMultipier, 200, 80 * buttonSizeMultipier, 30.0f * buttonSizeMultipier), "Dev")  )
			{
				ToggleDebugPanel();
			}

			if (GUI.Button(  new Rect( Screen.width - 40 * buttonSizeMultipier, 300, 40 * buttonSizeMultipier, 30.0f * buttonSizeMultipier), "RLog")  )
			{
				//
                if (RuntimeLog.Instance.m_LogBody.activeSelf)
                    RuntimeLog.HideLogBaord();
                else
                    RuntimeLog.ShowLogBoard();
			}

//			if (GUI.Button(  new Rect(Screen.width - 60 * buttonSizeMultipier, 250, 80 * buttonSizeMultipier, 30.0f * buttonSizeMultipier), "Tex")  )
//			{
//				StageManagerWrapper.bTestCheckTexture = !StageManagerWrapper.bTestCheckTexture;
//			}

			if (BuilderIsOn)
			{
				if (BuilderStatus == 1)
				{
					for (int i = 1; i < 7; i++)
					{
						if (GUI.Button(new Rect(i * BuilderCMDBtnWidth, 0 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), i.ToString()))
						{
							firstDice = i;
							BuilderStatus = 2;
						}
					}
				}

				if (BuilderStatus == 2)
				{
					for (int i = 1; i < 7; i++)
					{
						if (GUI.Button(new Rect(i * BuilderCMDBtnWidth, 1 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), i.ToString()))
						{
							secondDice = i;
							//CNetworkManager.Instance.SendRequest("Dice;" + firstDice + ";" + i);
							BuilderStatus = 3;
						}
					}
				}

				if (BuilderStatus == 3)
				{
					for (int i = 0; i < 2; i++)
					{
						if (i == 0 && GUI.Button(new Rect((i + 1) * BuilderCMDBtnWidth, 2 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), "Off"))
						{
							CNetworkManager.Instance.SendRequest("Dice;" + firstDice + ";" +secondDice+";false");
							BuilderStatus = 0;
						}

						if (i == 1 && GUI.Button(new Rect((i + 1) * BuilderCMDBtnWidth, 2 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), "On"))
						{
							CNetworkManager.Instance.SendRequest("Dice;" + firstDice + ";" + secondDice + ";true");
							BuilderStatus = 0;
						}
					}
				}

                if (BuilderStatus == 4)
                {
                    for (int i = 1; i < 7; i++)
                    {
                        if (GUI.Button(new Rect(i * BuilderCMDBtnWidth, 0 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), i.ToString()))
                        {
                            CNetworkManager.Instance.SendRequest("DirDice;" + i);
                            BuilderStatus = 0;
                        }
                    }
                }

                if (BuilderStatus == 5)
                {
                    for (int i = 1; i < 7; i++)
                    {
                        if (GUI.Button(new Rect(i * BuilderCMDBtnWidth, 0 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), i.ToString()))
                        {
                            firstDice = i;
                            BuilderStatus = 6;
                        }
                    }
                }

                if (BuilderStatus == 6)
                {
                    for (int i = 1; i < 7; i++)
                    {
                        if (GUI.Button(new Rect(i * BuilderCMDBtnWidth, 1 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), i.ToString()))
                        {
                            CNetworkManager.Instance.SendRequest("CombatDice;" + firstDice + ";" + i);
                            BuilderStatus = 0;
                        }
                    }
                }

				if (BuilderStatus >  0)
				{

					if(BuilderStatus==1)
					{
						if (GUI.Button(new Rect(2 * BuilderCMDBtnWidth, 3 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), "Clear NPC"))
						{
							if(!BattleManager.Instance.bCombatHappened)
								CNetworkManager.Instance.SendRequest("Clear;");
						}
					}

					if(UIManager.Instance.curDiceShape== DiceShapeType.Normal || UIManager.Instance.curDiceShape== DiceShapeType.Defender)
					{
						if (GUI.Button(new Rect(1 * BuilderCMDBtnWidth, 4 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), "Shuffle"))
						{
							SkillIndex = ++SkillIndex % SkillList.Count;
						}

						if (GUI.Button(new Rect(2 * BuilderCMDBtnWidth, 4 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), CSkillDataManager.Instance.FindSkillData(SkillList[SkillIndex]).name_kor + "(" + CSkillDataManager.Instance.FindSkillData(SkillList[SkillIndex]).cost + ")"))
						{
							if(BattleManager.Instance.bCombatHappened)
							{
								if(BattleManager.Instance.attacker == BoardManager.Instance.boardPerson_me)
									return;
							}
							if(SkillIndex<0 || SkillIndex>=SkillList.Count)
								return;
							CSkillData skillData = CSkillDataManager.Instance.FindSkillData(SkillList[SkillIndex]);
							if(skillData==null)
								return;

							if(BattleManager.Instance.bCombatHappened)
							{
								if(BattleManager.Instance.defender == BoardManager.Instance.boardPerson_me)
								{
									if(!skillData.can_use_defense_turn)
										return;
								}
							}

							PC_OP_USE_SKILL packet = new PC_OP_USE_SKILL();
							packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
							packet.SkillID = skillData.id;

							if (skillData.target_type == target_type.Enemy_Select)
							{
								SkillManager.Instance.WaitSelectTarget(true);
								SkillManager.Instance.ReserveSkillToCast(packet);
							}
							else
							{
								packet.TargetID = BoardManager.Instance.boardPerson_me.SID;
								//CNetworkManager.Instance.SendPacket(packet.Protocol, packet.GetParam());
								CNetworkManager.Instance.SendPacket(packet);
							}
						}
					}

					if(UIManager.Instance.curDiceShape== DiceShapeType.Normal || UIManager.Instance.curDiceShape== DiceShapeType.Defender)
					{
						if (GUI.Button(new Rect(3 * BuilderCMDBtnWidth, 7 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), "MP Full"))
						{
							CNetworkManager.Instance.SendRequest("FullMP;");
						}

						if (GUI.Button(new Rect(4 * BuilderCMDBtnWidth, 7 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), "HP 1 Me"))
						{
							CNetworkManager.Instance.SendRequest("LowHP;");
						}

						if (GUI.Button(new Rect(5 * BuilderCMDBtnWidth, 7 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), "HP 1 AI"))
						{
							CNetworkManager.Instance.SendRequest("LowHPAI;");
						}

						if (GUI.Button(new Rect(6 * BuilderCMDBtnWidth, 7 * BuilderCMDBtnHeight, BuilderCMDBtnWidth, BuilderCMDBtnHeight), "QA Log"))
						{
	                        CNetworkManager.Instance.SendRequest("QALog;");
						}
					}
				}

			}
		}
#if UNITY_EDITOR		
		if  ((m_Scene == SCENE.LoadingScene||m_Scene == SCENE.MainScene) && GUI.Button(new Rect (Screen.width-75*buttonSizeMultipier ,30.0f*buttonSizeMultipier ,75.0f*buttonSizeMultipier ,30.0f* buttonSizeMultipier),"Replay")){
            CSceneManager.isReplay = true;
			//CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
			//c.GoToWaitroomScene();			
			System.GC.Collect();
			System.GC.WaitForPendingFinalizers();
			Resources.UnloadUnusedAssets();
			Application.LoadLevel("BoardMap");
        }
#endif
		if  ((m_Scene == SCENE.LoadingScene||m_Scene == SCENE.MainScene) && GUI.Button(new Rect (Screen.width-75*buttonSizeMultipier ,70.0f*buttonSizeMultipier ,75.0f*buttonSizeMultipier ,30.0f* buttonSizeMultipier),"ReplayTut")){
			CSceneManager.isReplay = true;
			CSceneManager.isIngameTutorial = true;
			//CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
			//c.GoToWaitroomScene();			
			System.GC.Collect();
			System.GC.WaitForPendingFinalizers();
			Resources.UnloadUnusedAssets();
			Application.LoadLevel("BoardMap");
		}

		if (m_Scene == SCENE.PVP_MakeRoomScene21 || m_Scene == SCENE.PvPMakeRoomScene)
		{

            if (GUI.Button(new Rect(Screen.width - 120 * buttonSizeMultipier, 150 * buttonSizeMultipier, 120 * buttonSizeMultipier, 30.0f * buttonSizeMultipier), CSceneManager.StageElement))
            {
                
            }
            if (GUI.Button(new Rect(Screen.width - 120 * buttonSizeMultipier, 180 * buttonSizeMultipier, 120 * buttonSizeMultipier, 30.0f * buttonSizeMultipier), "AIFreeze"))
            {
                CNetworkManager.Instance.SendRequest("AIFreeze;");
            }
            if (GUI.Button(new Rect(Screen.width - 120 * buttonSizeMultipier, 210 * buttonSizeMultipier, 120 * buttonSizeMultipier, 30.0f * buttonSizeMultipier), "NPCSpawn"))
            {
                CNetworkManager.Instance.SendRequest("NPCSpawn;");
            }
            if (GUI.Button(new Rect(Screen.width - 120 * buttonSizeMultipier, 240 * buttonSizeMultipier, 120 * buttonSizeMultipier, 30.0f * buttonSizeMultipier), "Shuffle"))
            {
                TempSkillIndex = ++TempSkillIndex % TempSkillList.Count;
            }
            if (GUI.Button(new Rect(Screen.width - 120 * buttonSizeMultipier, 270 * buttonSizeMultipier, 120 * buttonSizeMultipier, 30.0f * buttonSizeMultipier), CSkillDataManager.Instance.FindSkillData(TempSkillList[TempSkillIndex]).name_kor))
            {
                CNetworkManager.Instance.SendRequest("TempSkill;" + CSkillDataManager.Instance.FindSkillData(TempSkillList[TempSkillIndex]).id);
            }
			

			
		}
		#endregion	
	}
	
	IEnumerator ShowGameOverTest()
	{
		yield return new WaitForSeconds(2.0f);
		//BoardManager.Instance.ShowGameOver(false,0, null, null,null,null);
		StageManagerWrapper.SendLeave();
	}

	public void SendGameInvite(string friendName)
	{
		PC_CS_INVITE_FRIEND packet = new PC_CS_INVITE_FRIEND();
		packet.FriendNickName = friendName;
		CNetworkManager.Instance.SendPacket(packet);
	}

	public void SendSelectedGameOrder(int index)
	{
		PC_CS_SELECT_ORDER_CARD packet = new PC_CS_SELECT_ORDER_CARD();
		packet.ServerID = BoardManager.Instance.boardPerson_me.SID;
		packet.Index = index;
		CNetworkManager.Instance.SendPacket(packet);
	}

	public void SendSelectedTempSkill(int skillId)
	{
		PC_CS_SELECT_TEMP_SKILL packet = new PC_CS_SELECT_TEMP_SKILL();
		packet.TempSkillID = skillId;
		CNetworkManager.Instance.SendPacket(packet);
	}
	
	private void UpdateUserData()
	{
        LoadingWindow.window.ShowShortLoading();
		RestAPI.singleton.PutUserData(UpdateUserDataCallback);
//		StartCoroutine("UpdateUserDataToWeb");
	}

	void UpdateUserDataCallback(Hashtable t)
	{
		RefreshUserData();
		if( Application.loadedLevelName == "08_UI_PvP_RoomWaiting" )
		{
			RoomWaitingSceneManager manager = GameObject.Find("RoomWaitingSceneManager").GetComponent<RoomWaitingSceneManager>();
			manager.hpPotionCount.text = MyInfo.Instance.HPPotion.ToString();
			manager.evolutionPotionCount.text = MyInfo.Instance.ResurrectPotion.ToString();
		}
	}

	void DeleteUnit(Hashtable t)
	{
		RequestMyUnitListInfo();
		GoToDeckEditScene();
	}

	internal void SubmitAddUnit()
	{
		StartCoroutine("AddUnit");
	}

	IEnumerator AddUnit()
	{
		WWWForm form = new WWWForm();

		form.AddField("UserId", MyInfo.Instance.DBID);
		form.AddField("UnitId", addedUnit);

		WWW www = new WWW(CSceneManager.WEB_SERVER_URL + "/api/unit", form);
		yield return www;

		if (www.error == null)
		{
			//StartCoroutine("RefreshDeckInfoToWeb");
			glog.debug("Add Unit OK");
			RequestMyUnitListInfo();
		}
		else
		{
			glog.debug(www.url);
			glog.debug("Post!!!!!!!!!!!!! Error");
			glog.debug(www.error);
		}

	}

	internal void DeleteUnit()
	{
		//RESTAPI -- 
		//StartCoroutine("DelUnit");
	}

	IEnumerator DelUnit()
	{
		WWWForm form = new WWWForm();

		form.AddField("UserId", MyInfo.Instance.DBID);
		form.AddField("UnitId", addedUnit);

		WWW www = new WWW(CSceneManager.WEB_SERVER_URL + "/api/unit", form);
		yield return www;

		if (www.error == null)
		{
			//StartCoroutine("RefreshDeckInfoToWeb");
			glog.debug("Add Unit OK");
			RequestMyUnitListInfo();
		}
		else
		{
			glog.debug(www.url);
			glog.debug("Post!!!!!!!!!!!!! Error");
			glog.debug(www.error);
		}

	}

	public void RefreshUserData()
	{
        LoadingWindow.window.ShowShortLoading();
		RestAPI.singleton.RefreshUserData(ReturnCallback);
        RestAPI.singleton.GetPVEStageInfo(ReturnCallback);
	}

	void ReturnCallback(Hashtable returnData)
	{
		LoadingWindow.window.HideLoading();
		switch ((RestAPIProtocol)returnData["protocol"])
		{
            case RestAPIProtocol.REFRESHUSERINFO:
				RestAPI.singleton.GetCurrentStaminaInfo(ReturnCallback);
				break;
			case RestAPIProtocol.GETCURRENTSTAMINAINFO:
                LoadingWindow.window.HideLoading();
				LoadUserDataFromWeb = true;
				break;
            case RestAPIProtocol.GETMYUNITLIST:
                RestAPI.singleton.RefreshMyDeckInfo(ReturnCallback);
				break;
			case RestAPIProtocol.REFRESHMYDECKINFO:
                LoadingWindow.window.HideLoading();
                CSceneManager.LoadDoneFromWebServer = true;
				break;
			case RestAPIProtocol.PUTUSERDATA:
                LoadingWindow.window.HideLoading();
				break;
			case RestAPIProtocol.SENDMYDECKCHANGEINFO:
				LoadingWindow.window.HideLoading();
				break;
			case RestAPIProtocol.SENDFACEBOOKINFO:
				GoToLoadingScene();
				break;
			case RestAPIProtocol.SENDDEVICEPUSHTOKEN:
#if UNITY_PHONE
				byte[] token = NotificationServices.deviceToken;
				if( token != null )
				{
					string tokenString = System.BitConverter.ToString(token).Replace("-", "").ToLower();
					PlayerPrefs.SetString("pushToken", tokenString);
				}
#endif
            break;
            case RestAPIProtocol.GETPVESTAGEINFO:
			break;
		}
	}
	
	public void MessagePopupCallback(MESSAGEPOPUPTYPE type, bool isYes)
	{
		if( isYes )
		{
			if( type == MESSAGEPOPUPTYPE.FacebookConnect )
			{
				GoToLoadingScene();
			}
		}
		else
		{
			if( type == MESSAGEPOPUPTYPE.FacebookConnect )
			{
				RestAPI.singleton.SendFacebookInfo(ReturnCallback, true);
			}
			else if( type == MESSAGEPOPUPTYPE.ClientCrashorException )
			{
				string fileContents = _logString + "\n\n" + _stackTrace;
				string fileName = string.Format("CrashReport_{1}_{2}_{3}_{4}_{5}_{6}_{7}.txt", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
				string FN = string.Format("{0}/{1}", SystemCore.GetAssetPath(), fileName);
				LCFileManager.FileWriteAllText(FN, fileContents);
			}
		}
	}

    void OnApplicationPause(bool paused)
    {
    }

	public static long TimeOffset = 0;

	public static byte UserInputMode = 0;

    internal void RequestRedirectJoin(byte RedirectJoinType, string RedirectAddress, string RoomName, string MapName, string FriendName, int StageID)
	{
        StartCoroutine(ProcessRedirectJoin(RedirectJoinType, RedirectAddress, RoomName, MapName, FriendName, StageID));
	}

    public IEnumerator ProcessRedirectJoin(byte RedirectJoinType, string RedirectAddress, string RoomName, string MapName, string FriendName, int StageID)
    {
        Debug.LogError("in ProcessRedirectJoin()");

        while (CNetworkManager.Instance.Connected)
        {
            yield return new WaitForSeconds(0.01f);
        }

        Debug.LogError(RedirectAddress);
        Debug.LogError(RoomName);
        Debug.LogError(MapName);

        CNetworkManager.Instance.m_PhotonPeer.Connect(RedirectAddress, "Game");

        while (!CNetworkManager.Instance.Connected)
        {
            yield return new WaitForSeconds(0.01f);
        }

        CSceneManager.SendVersionPacket();

        while (!CSceneManager.VersionCheckSuccess && !CSceneManager.LoginSuccess)
        {
            yield return new WaitForSeconds(0.01f);
        }

        PC_OP_JOIN packet = new PC_OP_JOIN();

        packet.JoinType = RedirectJoinType;
        packet.MapName = MapName;
        packet.RoomName = RoomName;
        packet.FriendName = FriendName;
        packet.StageID = StageID;

        CNetworkManager.Instance.SendPacket(packet);
    }

    internal void RequestRedirectLogin(string RedirectAddress)
    {
        StartCoroutine(ProcessRedictLogin(RedirectAddress));
    }

    public IEnumerator ProcessRedictLogin(string RedirectAddress)
    {
        Debug.LogError("in ProcessRedictLogin()");

        while (CNetworkManager.Instance.Connected)
        {
            yield return new WaitForSeconds(0.01f);
        }

        Debug.LogError(RedirectAddress);

        CNetworkManager.Instance.m_PhotonPeer.Connect(RedirectAddress, "Game");

        while (!CNetworkManager.Instance.Connected)
        {
            yield return new WaitForSeconds(0.01f);
        }

        CSceneManager.SendVersionPacket();

        while (!CSceneManager.VersionCheckSuccess && !CSceneManager.LoginSuccess)
        {
            yield return new WaitForSeconds(0.01f);
            /* TODO : failover */
        }
    }

    internal void RequestJoinToMaster(JoinType joinType, string p1, string m_mapName, string FriendName, int StageID = 0)
    {
        CNetworkManager.Instance.Disconnect();
      
        StartCoroutine(RelayToRedirectServer(joinType, p1, m_mapName, FriendName, StageID));
    }
    
    public IEnumerator RelayToRedirectServer(JoinType joinType, string p1, string m_mapName, string FriendName, int StageID = 0)
    {
        while (CNetworkManager.Instance.Connected)
        {
            yield return new WaitForSeconds(0.01f);
        }

        {
            
            CNetworkManager.Instance.ConnectToServer();
            
            while (!CNetworkManager.Instance.Connected)
            {
                yield return new WaitForSeconds(0.01f);
            }
        }

        CSceneManager.SendVersionPacket();

        while (!CSceneManager.VersionCheckSuccess && !CSceneManager.LoginSuccess)
        {
            yield return new WaitForSeconds(0.01f);
        }
        
        //if (CNetworkManager.Instance.JoinDataCached)
        {
            PC_OP_JOIN packet = new PC_OP_JOIN();

            packet.JoinType = (byte)joinType;
            packet.MapName = m_mapName;
            packet.RoomName = p1;
            packet.FriendName = FriendName;
            packet.StageID = StageID;
            CNetworkManager.Instance.SendPacket(packet);
        }
    }

    public static bool NeedToDisconnect = false;
}

